import React, { FC, ReactNode } from 'react';
import { FormStoreContext } from './config';
import { FormStore } from '.';
import Field, { IProps as FieldProps } from './Field';

const { Provider } = FormStoreContext;

interface IProps {
  store: FormStore;
  onFinish?: () => void;
  children?: ReactNode;
}

type FCC<T> = {
  Field: FC<FieldProps>;
} & FC<T>;

const Form: FCC<IProps> = ({ store, onFinish, children }) => {
  return (
    <Provider value={store}>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          const type = e.type;
          store.validate();
          if (type === 'submit') {
            onFinish && onFinish();
          }
        }}
      >
        {children}
      </form>
    </Provider>
  );
};

Form.Field = Field;

export default Form;
